<?php

namespace App\Http\Controllers\Api;

use App\Dengje\Utils\Settings;
use App\Dengje\Utils\Utils;
use App\Dengje\WeixinPay\WeixinPay;
use App\Models\WxShopAddress;
use App\Models\WxShopCart;
use App\Models\WxShopOrder;
use App\Models\WxShopOrderAfter;
use App\Models\WxShopOrderGoods;
use App\Models\WxUser;
use Illuminate\Http\Request;


class ShopOrderController extends BaseController
{
    /**
     * SHOP下单地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function order(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;
        $user_remark = $request->user_remark;
        $goods_amount = $request->goods_amount;
        $discounts_amount = $request->discounts_amount;
        $order_amount = $request->order_amount;
        $order_goods = $request->order_goods;

        $orderSn = (new Utils())->getSn(1);//生成订单号
        $addsinfo = WxShopAddress::where('user_id', $uid)->where('id', $aid)->first();//获取配送地址

        //生成SHOP订单
        $model = new WxShopOrder();
        $model->user_id = $uid;
        $model->order_id = $orderSn;//订单号
        $model->goods_amount = $goods_amount;//商品总价
        $model->discounts_amount = $discounts_amount;//优惠金额
        $model->order_amount = $order_amount;//订单总额
        $model->adds_name = $addsinfo['name'];//收货人姓名
        $model->adds_mobile = $addsinfo['mobile'];//收货人电话
        $model->address = $addsinfo['province'] . $addsinfo['city'] . $addsinfo['county'] . $addsinfo['adds'];//收货详细地址
        $model->user_remark = $user_remark;//用户备注
        $model->pay_status = 1;//支付状态 1=未付款 2=已付款 3=已退款
        $model->status = 0;//发货状态 0=正常 1=未发货 2=已发货 3=确认收货 4=已退货 5=取消
        $model->save();

        $orderId = $model->id;//获取订单id

        //批量添加订单商品
        $orderGoods = [];
        foreach ($order_goods as $k => $v) {
            $orderGoods[$k]['pic'] = $v['goods_pic'];
            $orderGoods[$k]['name'] = $v['goods_name'];
            $orderGoods[$k]['product'] = $v['goods_product'];
            $orderGoods[$k]['vip_price'] = $v['vip_price'];
            $orderGoods[$k]['price'] = $v['price'];
            $orderGoods[$k]['quantity'] = $v['num'];
            $orderGoods[$k]['order_id'] = $orderId;
            $orderGoods[$k]['goods_id'] = $v['goods_id'];
            $orderGoods[$k]['product_id'] = $v['product_id'];
            $orderGoods[$k]['created_at'] = date('Y-m-d H:i:s', time());
        }
        $ogModel = new WxShopOrderGoods();
        $ogModel->addAll($orderGoods);

        //修改购物车数据
        WxShopCart::where('user_id', $uid)->where('is_check', 1)->where('state', 0)
            ->update(['state' => 2]);


        //支付需要资料
        $openid = WxUser::where('id', $uid)->value('weixin_openid');
        $appid = Settings::get('app_id');
        $mch_id = Settings::get('mch_id');
        $key = Settings::get('mch_secret');
        $out_trade_no = $orderSn;
        $body = '轻航SHOP购物';
        $total_fee = $order_amount;

        // 发起支付
        $payObject = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);
        return $this->success($payObject->pay());
    }

    /**
     * Shop订单列表Count
     */
    public function getOrderCount(Request $request)
    {

        $uid = $request->uid;

        $payCount = WxShopOrder::where('user_id', $uid)
            ->where('pay_status', 1)->where('status', 0)
            ->count();

        $deliverCount = WxShopOrder::where('user_id', $uid)
            ->where('pay_status', 2)->where('status', 1)
            ->count();


        $closedCount = WxShopOrder::where('user_id', $uid)
            ->where('pay_status', 2)->where('status', 2)
            ->count();

        $data = [
            'payCount' => $payCount,
            'deliverCount' => $deliverCount,
            'closedCount' => $closedCount,
        ];

        return $this->success($data);
    }

    /**
     * Shop订单列表
     */
    public function getOrderList(Request $request)
    {

        $uid = $request->uid;
        $type = $request->type;

        $yesterday = date("Y-m-d H:i:s", strtotime("-2 hours"));

        //清除超时未支付订单
        WxShopOrder::where('user_id', $uid)->where('pay_status', 1)->where('status', 0)
            ->where('created_at', '<', $yesterday)
            ->update(['status' => 5]);

        if ($type == 1) {
            $data = WxShopOrder::where('user_id', $uid)
                ->where('pay_status', 1)->where('status', 0)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else if ($type == 2) {
            $data = WxShopOrder::where('user_id', $uid)
                ->where('pay_status', 2)->where('status', 1)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else if ($type == 3) {
            $data = WxShopOrder::where('user_id', $uid)
                ->where('pay_status', 2)->where('status', 2)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else if ($type == 4) {
            $data = WxShopOrder::where('user_id', $uid)
                ->where('pay_status', 2)->where('status', 3)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else {
            $data = WxShopOrder::where('user_id', $uid)
                ->where('status', '<>', 6)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        }

        $data->map(function ($v) {
            $v->goods = WxShopOrderGoods::where('order_id', $v->id)->get();
            $v->status_text = self::orderStatusText($v->pay_status, $v->status);
        });

        return $this->success($data);
    }

    /**
     * 订单状态
     * @param $pay_status
     * @param $status
     */
    public static function orderStatusText($pay_status, $status)
    {
        $text = '';
        if ($pay_status == 1 && $status == 0) {
            $text = '待支付（2h内有效）';
        } else if ($pay_status == 2 && $status == 1) {
            $text = '待发货';
        } else if ($pay_status == 2 && $status == 2) {
            $text = '待收货';
        } else if ($pay_status == 2 && $status == 3) {
            $text = '待晒单';
        } else if ($pay_status == 1 && $status == 5) {
            $text = '已取消';
        } else if ($pay_status == 3 && $status == 4) {
            $text = '已退款';
        }
        return $text;
    }

    /**
     * Shop删除订单
     */
    public function delOrder(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        WxShopOrder::where('user_id', $uid)->where('id', $oid)
            ->update(['status' => 6]);

        return $this->success();
    }

    /**
     * Shop取消订单
     */
    public function cancelOrder(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        WxShopOrder::where('user_id', $uid)->where('id', $oid)
            ->update(['status' => 5]);

        return $this->success();
    }

    /**
     * Shop重新付款
     */
    public function payment(Request $request)
    {
        $uid = $request->uid;

        $openid = WxUser::where('id', $uid)->value('weixin_openid');
        $appid = Settings::get('app_id');
        $mch_id = Settings::get('mch_id');
        $key = Settings::get('mch_secret');
        $out_trade_no = $request->orderSn;
        $body = '轻航SHOP购物';
        $total_fee = $request->order_amount;

        // 发起支付
        $payObject = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);
        return $this->success($payObject->pay());
    }

    /**
     * Shop催发货
     */
    public function pushDelivery(Request $request)
    {
        $uid = $request->uid;
        $on = $request->on;
        $title = $request->title;
        $message = $request->message;

        $isExists = WxShopOrderAfter::where('user_id', $uid)->where('order_id', $on)->where('state', 0)->exists();
        if ($isExists) {
            return $this->fail(800010);
        } else {
            $model = new WxShopOrderAfter();
            $model->user_id = $uid;
            $model->order_id = $on;
            $model->title = $title;
            $model->content = $message;
            $model->save();
            return $this->success();
        }
    }

    /**
     * Shop申请退款
     */
    public function orderRefund(Request $request)
    {
        $uid = $request->uid;
        $on = $request->on;
        $oid = $request->oid;
        $opid = $request->opid;
        $title = $request->title;
        $message = $request->message;

        WxShopOrderGoods::where('order_id', $oid)->where('product_id', $opid)
            ->update(['state' => 1]);

        $model = new WxShopOrderAfter();
        $model->user_id = $uid;
        $model->order_id = $on;
        $model->title = $title;
        $model->content = $message;
        $model->save();

        return $this->success();
    }

    /**
     * Shop退货退款
     */
    public function refundGoods(Request $request)
    {
        $uid = $request->uid;
        $on = $request->on;
        $oid = $request->oid;
        $opid = $request->opid;
        $title = $request->title;
        $message = $request->message;

        WxShopOrderGoods::where('order_id', $oid)->where('product_id', $opid)
            ->update(['state' => 2]);

        $model = new WxShopOrderAfter();
        $model->user_id = $uid;
        $model->order_id = $on;
        $model->title = $title;
        $model->content = $message;
        $model->save();

        return $this->success();
    }

    /**
     * Shop确认收货
     */
    public function confirmReceipt(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        WxShopOrder::where('user_id', $uid)->where('id', $oid)
            ->update(['status' => 3]);

        return $this->success();
    }


}
